# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__ = "root"
__date__ = "$Sep 23, 2009 8:25:02 PM$"

import pycurl
import StuClass
import random
import re
import hmac
import hashlib
import sql
import xdrlib

#def new( user, password ):
#    return StudentA( user, password )

def New( id, user, password ):
    return Student( id, user, password )

class Student:
    def __init__(self, id, user, password):

        self.SQLId = id
        self.user = user
        self.password = password

        self.contents = ''
        self.pstoken = 0
        self.pw = ''
        self.pskey = ''
        self.x = str(random.randint(-10, 10) + 69)
        self.y = str(random.randint(-10, 10) + 21)

        self.classes = []
        self.gpa = 0.0
        self.quarter = 1

        self.curl = pycurl.Curl()
        self.curl.setopt(self.curl.WRITEFUNCTION, self.body_callback)
        self.curl.setopt(self.curl.COOKIEJAR, "cookies/cookie_"+ self.user + ".txt")

    def body_callback(self, buf):
        self.contents = self.contents + buf

    def clean_contents(self):
        self.contents = ''

    def open_main_page(self):
        self.curl.setopt(self.curl.URL, 'http://www.southamptonpowerschool.org/public/')

        self.curl.perform()

        self.load_data(self.contents)


    def load_data(self, Data):

        pstoken = re.findall(r"name=\"pstoken\" value=\"(.+)\"", Data, re.M)
        self.pstoken = pstoken[0]

        pskey = re.findall(r"var pskey = \"(.+)\"", Data, re.M)
        self.pskey = pskey[0]

        encrypt = hmac.new(self.pskey, self.password, hashlib.md5)
        self.pw = encrypt.hexdigest()

    def do_login(self):
        print("Login in with: " + self.user)

        self.curl.setopt(self.curl.URL, 'http://www.southamptonpowerschool.org/guardian/home.html')
        self.curl.setopt(self.curl.POSTFIELDS, 'pstoken=' + self.pstoken +
                         '&account=' + self.user +
                         '&pw=' + self.pw +
                         '&x='+self.x+'&y='+self.y)

        self.clean_contents()
        self.curl.perform()

        self.curl.setopt(self.curl.POSTFIELDS, '')
        self.clean_contents()
        self.curl.perform()

    def FetchGrades(self):

        
        for column in re.finditer("<tr align=\"center\" bgcolor=\"#(edf3fe|ffffff)\">(.+?)</tr>", self.contents, re.M):
            newclass = StuClass.StuClass()
            newclass.load_info( column.group(2) )

            self.classes.append( newclass )

        self.FetchGPA()

    def FetchGPA(self):
        GpaMatch = re.findall(r"<td align=\"center\">.+GPA [(]Q(.+)[)]: (.+)</td>", self.contents, re.M)

        if GpaMatch:
            self.quarter = GpaMatch[0][0]
            self.gpa = GpaMatch[0][1]

            return

        TotalSumGrades = 0
        GradeCount = 0

        for NewClass in self.classes:
            TotalSumGrades +=


    def InsertData(self):

        databuff = xdrlib.Packer()

        for NewClass in self.classes:
             NewClass.WriteToBuffer( databuff )
             print NewClass

        Data = sql.conn.escape_string( databuff.get_buffer() )
     
        cursor = sql.conn.cursor()
        cursor.execute("INSERT INTO ps_grades(`student`,`gpa`,`data`) VALUES("
            +str(self.SQLId)+","+ self.gpa +",'"+Data+"')")
        

    def __del__(self):
        self.curl.close()



